package com.zmx.common.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * @Description: Host工具类 IP/HOSTNAME
 * @ClassName: HostUtil
 * @Author zhaomxr
 * @Date 2021-12-01 15:00
 */
@Slf4j
public class HostUtil {

    public static String IP;
    public static String HOSTNAME;

    static {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            IP = inetAddress.getHostAddress();
            HOSTNAME = inetAddress.getHostName();
        } catch (UnknownHostException e) {
            log.error(e.getMessage(), e);
            IP = "UNKNOWN";
            HOSTNAME = "UNKNOWN";
        }

        if (Objects.equals(IP, "127.0.0.1") || Objects.equals(IP, "::1") || Objects.equals(IP, "UNKNOWN")) {
            try {
                Process process = Runtime.getRuntime().exec("hostname -i");
                if (process.waitFor() == 0) {
                    IP = new String(IOUtils.toByteArray(process.getInputStream()), "UTF-8");
                }

                process = Runtime.getRuntime().exec("hostname");
                if (process.waitFor() == 0) {
                    HOSTNAME = new String(IOUtils.toByteArray(process.getInputStream()), "UTF-8");
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        log.info("IP:{} HOSTNAME:{}", IP, HOSTNAME);
    }

    public static void main(String[] args) {
        System.out.println("IP:" + IP);
        System.out.println("HOSTNAME:" + HOSTNAME);
    }
}
